<template>
  <div class="dynamic-form">
    <el-form @submit.prevent="submitForm">
      <el-form-item v-for="(field, index) in config" :key="index" class="mb-4">
        <label class="block text-gray-700 text-sm font-bold mb-2">{{ field.label }}</label>
        <el-input
          v-if="field.type === 'input'"
          v-model="formValues[field.model]"
          :placeholder="field.placeholder"
        />
      </el-form-item>
      <el-button
        type="submit"
        class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
      >
        Submit
      </el-button>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

// 定义属性
const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  },
  config: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

// 表单数据
const formValues = ref({ ...props.modelValue })

// 监听表单数据变化并更新父组件
watch(
  formValues,
  (newValues) => {
    emit('update:modelValue', newValues)
  },
  { deep: true }
)

// 监听父组件传入的值变化
watch(
  () => props.modelValue,
  (newValues) => {
    formValues.value = { ...newValues }
  },
  { deep: true }
)

const submitForm = () => {
  console.log('Form submitted:', formValues.value)
}
</script>